package my.edu.model.commodity.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.log.Log;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import lombok.extern.slf4j.Slf4j;
import my.edu.common.constant.MessageConstant;
import my.edu.common.domain.PageDTO;
import my.edu.common.validate.groups.Insert;
import my.edu.common.domain.Response;
import my.edu.model.commodity.entity.Product;
import my.edu.model.commodity.entity.dto.ProductDTO;
import my.edu.model.commodity.entity.dto.ProductSearchDTO;
import my.edu.model.commodity.service.IProductService;
import my.edu.utils.OssUtil;
import my.edu.utils.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.ExecutionException;

@RequestMapping("/material")
@RestController
@Tag(name = "商品接口")
@Validated
@Slf4j
public class ProductController {

    @Autowired
    private IProductService productService;
    @Autowired
    private OssUtil ossUtil;


    @PutMapping
    @RequiresPermissions("product:save")
    @Operation(summary = "新增商品")
    public Response save(@Validated(value = Insert.class) @RequestBody ProductDTO productDTO) {
        productService.savenew(productDTO);
        return Response.success();
    }


    @GetMapping("/list")
    @Operation(summary = "获取商品列表")
    public Response getProduct(@ModelAttribute PageDTO pageDTO, @ModelAttribute ProductSearchDTO productSearchDTO) {
        return Response.success(productService.listAll(pageDTO, productSearchDTO));
    }

    @GetMapping("/one")
    @Operation(summary = "获取商品")
    public Response getProduct(Long id) {
        return Response.success(productService.getVOById(id));
    }


    @GetMapping("/getMaterialByNo")
    @Operation(summary = "根据编号获取商品信息")
    public Response getProductById(String productNo) {
        List<String> productNos =   Arrays.stream(productNo.split(",")).toList();
        return Response.success(productService.getVOByNos(productNos));
    }

    @GetMapping("/getMaterialByParam")
    @Operation(summary = "根据编号获取商品信息")
    public Response getMaterialByParam(String q) {
        return Response.success(productService.getVOByParam(q));
    }

    @PostMapping("/batchSetStatus")
    @RequiresPermissions(value = {"product:update"})
    @Operation(summary = "更新状态")
    public Response batchSetStatus(@RequestBody JSONObject jsonObject) {
        int status = jsonObject.getInt("status");
        String ids = jsonObject.getStr("ids");
        if (status != 0 && status != 1) {
            return Response.error("状态值错误");
        }
        List<Long> longs = StringUtils.strToLongList(ids);
        productService.setStatus(longs, status);
        return Response.success();
    }


    @PostMapping("/update")
    @RequiresPermissions("product:update")
    @Operation(summary = "更新商品信息")
    public Response update(@Valid @RequestBody ProductDTO productDTO) {
        productService.updateByDTO(productDTO);
        return Response.success();
    }

    @PostMapping("/upload")
    @Operation(summary = "添加图片")
    public Response upload(MultipartFile file) {
        try {
            //获取文件名
            String originalFilename = file.getOriginalFilename();
            //获取后缀名
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //生成新文件名
            String name = UUID.randomUUID().toString() + extension;
            //调用oss工具类方法，返回文件请求路径
            String upload = ossUtil.upload(file.getBytes(), name.toString());
            return Response.success(upload);
        } catch (IOException e) {
            log.error("文件上传失败：{}", e);
        }
        return Response.error(MessageConstant.UPLOAD_FAILED);
    }

    @GetMapping("/removeImg")
    @Operation(summary = "删除图片")
    public Response remove(String url) {
        ossUtil.remove(url);
        return Response.success();
    }

    @DeleteMapping("/deleteBatch")
    @RequiresPermissions("product:del")
    @Operation(summary = "批量删除商品")
    @Transactional
    public Response deleteBatch(String ids) {
        List<Long> longs = StringUtils.strToLongList(ids);
        List<Product> products = productService.listByIds(longs);
        boolean b = productService.removeBatchByIds(longs);
        if (b) for (Product product : products) {
            if (product.getImageUrl() != null && !product.getImageUrl().isEmpty())
                ossUtil.remove(product.getImageUrl());
        }
        return Response.success();
    }

    @DeleteMapping("/delete")
    @RequiresPermissions("product:del")
    @Operation(summary = "删除商品")
    public Response delete(Long id) {
        Product product = productService.getById(id);
        boolean b = productService.removeById(product);
        if (b &&
                product.getImageUrl() != null &&
                !product.getImageUrl().isEmpty()) ossUtil.remove(product.getImageUrl());
        return Response.success();
    }

    @GetMapping("/getListWithStock")
    @Operation(summary = "获取商品列表")
    @RequiresPermissions("product:get")
    public Response getListWithStock( String materialParam,Integer categoryId,@ModelAttribute PageDTO pageDTO ) throws ExecutionException, InterruptedException {
        return Response.success(productService.getListWithStock(pageDTO, materialParam, categoryId));
    }

    @GetMapping("/findStockWarningCount")
    @RequiresPermissions("product:get")
    public Response findStockWarningCount(@ModelAttribute PageDTO pageDTO )  {
        return Response.success(productService.findStockWarningCount(pageDTO));
    }

}